package le.ralph.quwen.cn.java.model.protocol;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class BaseProtocol {

    private Retrofit retrofit;
    private IHttpService httpService;

    public IHttpService getService() {
        return httpService;
    }

    public BaseProtocol() {
        retrofit = RetrofitManager.getInstance().getRetrofit();
        httpService = RetrofitManager.getInstance().getService();
    }

    /**
     * 执行网络请求
     *
     * @param call
     * @param callback
     * @param reqType 请求的是哪一个接口
     * @param clazz 请求json字符串后得到的javabean对象的类型
     */
    public <T> void execute(Call<JsonObject> call,
                            final HttpCallback callback,
                            final int reqType,
                            final Class<T> clazz) {
        call.enqueue(new Callback<JsonObject>() {

            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                String json = response.body().toString();
                // 手动解析json字符串
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    int status = jsonObject.getInt("status");
                    if (status == 0) {  // 请求成功
                        Gson gson = new Gson();
                        T bean = gson.fromJson(json, clazz);

                        if (callback != null) {
                            callback.onHttpSuccess(reqType, bean);
                        }

                    } else { // 非0为请求失败
                        String error = jsonObject.getString("error");
                        // showToast("error: " + error);

                        if (callback != null) {
                            callback.onHttpError(reqType, error);
                        }
                    }
                } catch(Exception e) {
                    e.printStackTrace();

                    if (callback != null) {
                        callback.onHttpError(reqType, e.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable e) {
                if (callback != null) {
                    callback.onHttpError(reqType, e.getMessage());
                }
            }
        });
    }

    /** 网络请求回调接口 */
    public interface HttpCallback {
        /**
         * 请求成功
         * @param reqType 请求哪一个接口
         * @param obj 请求返回的javabean对象
         */
        public void onHttpSuccess(int reqType, Object obj) ;

        /**
         * 请求失败
         * @param reqType 请求哪一个接口
         * @param error 失败原因
         */
        public void onHttpError(int reqType, String error) ;
    }

}